from playwright.sync_api import BrowserContext, Page, Error
from dotenv import load_dotenv
import os
import json

# 加载 .env 文件
load_dotenv()

# oxk 钱包密码
okx_password = os.getenv('OKX_PASSWORD')


# 获取插件信息
def get_extensions_info(page: Page, num):
    extensions = get_okx_extensions(num)
    # 导航到你的页面，例如 chrome://extensions/
    if extensions:
        page.close()
        return extensions
    page.goto("chrome://extensions/")
    # 找到 class 为 "items-container" 的 div 元素下的所有 "extensions-item"
    items_container = page.locator(".items-container")
    extension_items = items_container.locator("extensions-item").all()
    # 遍历每个 "extensions-item" 元素
    for item in extension_items:
        # 获取 "extensions-item" 的 ID
        item_id = item.get_attribute("id")
        if item_id:
            # 获取 "extensions-item" 下的 "name-and-version" 元素的文本
            try:
                name_and_version_text = item.locator("#name").text_content()
                if '欧易 Web3 钱包' in name_and_version_text:
                    # 将扩展信息添加到结果字典
                    extensions[item_id] = name_and_version_text
            except Exception as e:
                print(f"Error getting name and version for item {item_id}: {e}")
    page.close()
    # 创建目录
    dir_path = 'D:/chromeFile/extensions/'
    if not os.path.exists(dir_path):
        os.makedirs(dir_path)
    # 保存到文件
    with open('D:/chromeFile/extensions/extensions_{}.json'.format(num), 'w') as f:
        json.dump(extensions, f)
    return extensions


# 查找欧易钱包的扩展ID
def find_okx_extension_id(extensions):
    for key, value in extensions.items():
        if '欧易 Web3 钱包' in value:
            return key
    return ''


def get_okx_extensions(num):
    # 尝试读取文件中的拓展id
    if os.path.exists('D:/chromeFile/extensions/extensions_{}.json'.format(num)):
        with open('D:/chromeFile/extensions/extensions_{}.json'.format(num), 'r') as f:
            extensions = json.load(f)
            return extensions
    return {}


# 页面创建完成监听事件
def do_oxk_page(page: Page, num) -> None:
    # 判断是否为欧易钱包页面
    extension_id = find_okx_extension_id(get_okx_extensions(num))
    if not extension_id:
        print('oxk 拓展信息获取失败')
        return
    # 等待一段时间，让操作完成
    page.wait_for_timeout(2000)
    # 解锁钱包
    if f'chrome-extension://{extension_id}/popup.html' in page.url:
        unlock_wallet_and_fill_password(page)
    if f'chrome-extension://{extension_id}/notification.html' in page.url:
        confirm_signature(page)


# 解锁钱包
def unlock_wallet_and_fill_password(page: Page) -> None:
    # 判断是否需要解锁钱包
    if page.locator('text=解锁').count() > 0:
        print('需要解锁钱包')
        # 尝试找到密码输入框
        try:
            password_input = page.wait_for_selector("input.okui-input-input[type='password']")
            password_input.fill(okx_password)
            # 提交表单
            submit_button = page.locator("button[type='submit']")
            submit_button.click()
            # 等待一段时间，让操作完成
            page.wait_for_timeout(2000)
            page.close()
        except Error as e:
            if "No node found for selector" in str(e):
                print("Unlock Wallet button not found. Skipping password fill and unlock.")
            else:
                raise
        print('解锁 okx 钱包成功')
    else:
        print('不需要解锁钱包')


# 确认签名
def confirm_signature(page: Page) -> None:
    # 定位包含 "X-Address" 的元素
    locator_xaddress = page.locator('//div[contains(@class, "_typography-text") and contains(text(), "X-Address")]')
    if locator_xaddress.count() > 0:
        text_content = locator_xaddress.inner_text()
        print(f"请签名的地址为: {text_content}")
        # 定位包含 "确认" 的元素
        locator_confirm = page.locator('//div[contains(text(), "确认")]')
        if locator_confirm.count() > 0:  # 检查至少有一个匹配的元素
            try:
                if locator_confirm.is_visible():
                    locator_confirm.click()  # 点击确认按钮
                    print("确认按钮被点击。")
            except Exception as e:
                print(f"点击确认按钮时发生错误: {e}")
        else:
            print("未找到包含 '确认' 的元素。")
    else:
        print("未找到包含 'X-Address' 的元素。")


def login_okx(context: BrowserContext, num):
    print('开始解锁 okx 钱包')
    # 获取并且保存拓展id
    extension_id = find_okx_extension_id(get_extensions_info(context.new_page(), num))
    if extension_id:
        page = context.new_page()
        # 访问oxk扩展页面
        page.goto(f"chrome-extension://{extension_id}/popup.html")
